Imports System.Xml
Imports System.Net
Imports System.IO
Imports System.Text.RegularExpressions
Imports VS.XpathTester


Public Class frmMain
  Dim XmlDoc As XmlDocument
    Dim HistoryHash As Hashtable

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        HistoryHash = New Hashtable()
    End Sub

    Private Sub btnUseXPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUseXPath.Click
        If Trim(txtXpath.Text) <> "" Then
            Try
                XmlDoc = New XmlDocument
                XmlDoc.PreserveWhitespace = True
                XmlDoc.LoadXml(txtXML.Text)
                Dim xmlNodes As XmlNodeList
                Dim xmlNode As XmlNode
                xmlNodes = XmlDoc.SelectNodes(txtXpath.Text)
                If xmlNodes Is Nothing Then
                    txtResult.Text = "Error in XPath or not Result returned"
                    txtResult.BackColor = Color.FromArgb(251, 90, 90)
                Else
                    Dim ctr As Integer = 0
                    txtResult.Text = ""
                    For Each xmlNode In xmlNodes
                        ctr += 1
                        txtResult.Text &= " *** Start of Node Data *** " & vbCrLf & xmlNode.OuterXml.ToString & _
                            vbCrLf & " *** Start of Node Data *** " & vbCrLf & vbCrLf
                    Next
                    If ctr = 0 Then
                        ResetTxtXML()
                        txtResult.BackColor = Color.FromArgb(251, 90, 90)
                    Else
                        'Add to History
                        AddXPathToHistory()
                        txtResult.BackColor = Color.FromArgb(191, 244, 189)

                        Dim syntaxer As New SyntaxHighlight
                        syntaxer.HightlightText(txtResult)
                        'txtResult.ForeColor = Color.White
                    End If
                End If
            Catch ex As XmlException
                MsgBox("There is an error using XML" & vbCrLf & ex.Message)
            Catch ex As Exception
                MsgBox("An Unknown Error has occured using XML " & vbCrLf & ex.Message)
            End Try
        End If
    End Sub

    Private Sub OpenFile()
        OpenXML.FileName = ""
        OpenXML.ShowDialog()
        txtXML.Text = ""
        If Trim(OpenXML.FileName) <> "" Then
            Dim tmpXml As XmlDocument
            tmpXml = New XmlDocument
            Try
                tmpXml.PreserveWhitespace = True
                tmpXml.Load(OpenXML.FileName)
                PopulateData(tmpXml.OuterXml)
            Catch ex As Exception
                MsgBox("Fail to load XML 111" & ex.Message)
                ResetTxtXML()
            End Try
        End If
    End Sub

    Private Sub OpenUrl()
        Dim Url As String
        Dim DefaultValue As String = "http://"
        Url = InputBox("Enter the URL you want to Access", "VS XPath Tester", DefaultValue)
        If Trim(Url) = "" OrElse Trim(Url.ToLower) = DefaultValue.ToLower Then
            Url = ""
            ResetTxtXML()
        Else
            'Make a Online Request
            Try
                Me.Cursor = Cursors.WaitCursor
                Dim request As HttpWebRequest = CType(WebRequest.Create(Url), HttpWebRequest)
                Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
                If response.StatusCode = HttpStatusCode.OK Then
                    Dim stm As Stream = response.GetResponseStream()
                    Dim sr As New StreamReader(stm)
                    Dim str As String = ""
                    str = sr.ReadToEnd
                    'While sr.Peek > -1
                    '  str &= sr.ReadLine & vbCrLf
                    '  'str has complete line in it.
                    'End While
                    PopulateData(str)
                    'txtXML.Text = str
                Else
                    MsgBox("Fail to retrieve information from " & vbCrLf & Url)
                End If
            Catch ex As Exception
                MsgBox("Fail to retrieve information from " & vbCrLf & Url & vbCrLf & "due to execpetion as follow " & vbCrLf & ex.Message)
            Finally
                Me.Cursor = Cursors.Arrow
            End Try

        End If
    End Sub

    Private Sub PopulateData(ByVal XMLData As String)
        Dim populate As New PopulateControls
        Dim xmldoc As New XmlDocument
        Dim syntaxer As New SyntaxHighlight
        txtXML.Text = XMLData
        syntaxer.HightlightText(txtXML)
        xmldoc.LoadXml(XMLData)
        tvwMainXml.Nodes.Clear()
        populate.PopulateTreeFromXML(tvwMainXml, xmldoc)
    End Sub

    Private Sub btnOpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        OpenFile()
    End Sub

    Private Sub btnOnlineXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        OpenUrl()
    End Sub

    Private Sub ResetTxtXML()
        txtResult.Text = ""
        txtResult.BackColor = Color.White
        txtResult.ForeColor = Color.Black
    End Sub

    Private Sub AddXPathToHistory()
        Dim myKey As String = ""
        If (txtXpath.Text.Length > 25) Then
            myKey = txtXpath.Text.Substring(0, 15) + " ... " + txtXpath.Text.Substring(txtXpath.Text.Length - 5, 5)
        Else
            myKey = txtXpath.Text
        End If
        If HistoryHash(myKey) Is Nothing Then
            HistoryHash.Add(myKey, txtXpath.Text)
        Else
            HistoryHash(myKey) = txtXpath.Text
        End If

        ddlHistory.DropDownItems.Clear()
        'cmHistory.Items.Clear()
        For Each key As String In HistoryHash.Keys
            If Not HistoryHash(key) Is Nothing Then
                ddlHistory.DropDownItems.Add(key)
                'cmHistory.Items.Add(key)
                AddHandler ddlHistory.DropDownItems.Item(ddlHistory.DropDownItems.Count - 1).Click, AddressOf ddlHistory_Event
            End If
        Next
    End Sub

    Private Sub ddlHistory_Event(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If sender.GetType.ToString = "System.Windows.Forms.ToolStripMenuItem" Then
            Dim menu As ToolStripItem = CType(sender, ToolStripItem)
            txtXpath.Text = HistoryHash(menu.Text)
        End If
    End Sub

    Private Sub OpenFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenFileToolStripMenuItem.Click
        OpenFile()
    End Sub

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        OpenUrl()
    End Sub

    Private Sub VisitVikasumitcomToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VisitVikasumitcomToolStripMenuItem.Click
        Process.Start("http://www.vikasumit.com")
    End Sub

    Private Sub AboutXPathTesterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutXPathTesterToolStripMenuItem.Click
        Dim x As New frmAboutBox
        x.ShowDialog()
    End Sub

    Private Sub CloseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseToolStripMenuItem.Click
        End
    End Sub

    Private Sub HelpToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelpToolStripMenuItem1.Click
        Dim str As String = "Thanks for using Xpath Tester. It is very simple to use utility to test your XPath." & _
        " All you have do is Load your XML either by giving its web URL or File on disk. If you donot have either of two, simple type in your XML in " & _
        "given area. Now On first TextBox, simple write the XPath you want to execute on your XML, if it found any positive result it will display the output " & _
        "in given below box with green background otherwise it display either a message box with error (if XML reading fail) or Red background of result area, if no match is found" & _
        vbCrLf & vbCrLf & "Hope you will find this Application useful. If so, you can send us an email at support@vikasumit.com, so we can continue building such application." & _
        vbCrLf & vbCrLf & "Thanks again for using our application"
        MsgBox(str)
    End Sub

    Private Sub VisitVsXpathTesterHomeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VisitVsXpathTesterHomeToolStripMenuItem.Click
        Process.Start("http://vsxpathtester.codeplex.com")
    End Sub

    Private Sub tsbtnFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnFile.Click
        OpenFile()
    End Sub

    Private Sub tsbtnOnlineXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnOnlineXML.Click
        OpenUrl()
    End Sub

    Private Sub btnHistory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        cmHistory.Show()
    End Sub
End Class